-- Tags: no-parallel

DROP DATABASE IF EXISTS db1_02703;
DROP USER IF EXISTS u1_02703;
CREATE USER u1_02703;

CREATE DATABASE db1_02703;

CREATE TABLE db1_02703.02703_rqtable (x UInt8) ENGINE = MergeTree ORDER BY x;
INSERT INTO db1_02703.02703_rqtable VALUES (1), (2), (3), (4);


SELECT '-- row policies for database';
CREATE ROW POLICY db1_02703 ON db1_02703.* USING 1 AS PERMISSIVE TO ALL;
CREATE ROW POLICY tbl1_02703 ON db1_02703.table USING 1 AS PERMISSIVE TO ALL;
SELECT '  -- SHOW CREATE POLICY db1_02703 ON db1_02703.*';
SHOW CREATE POLICY db1_02703 ON db1_02703.*;
SELECT '  -- SHOW CREATE POLICY ON db1_02703.*';
SHOW CREATE POLICY ON db1_02703.*;
SELECT '  -- SHOW CREATE POLICY ON db1_02703.`*`';
SHOW CREATE POLICY ON db1_02703.`*`;
DROP POLICY db1_02703 ON db1_02703.*;
DROP POLICY tbl1_02703 ON db1_02703.table;

CREATE ROW POLICY any_02703 ON *.some_table USING 1 AS PERMISSIVE TO ALL; -- { clientError 62 }

CREATE TABLE 02703_rqtable_default (x UInt8) ENGINE = MergeTree ORDER BY x;

CREATE ROW POLICY 02703_filter_11_db ON * USING x=1 AS permissive TO ALL;
CREATE ROW POLICY 02703_filter_11 ON 02703_rqtable_default USING x=2 AS permissive TO ALL;

INSERT INTO 02703_rqtable_default VALUES (1), (2), (3), (4);

SELECT 'R1, R2: (x == 1) OR (x == 2)';
SELECT * FROM 02703_rqtable_default;

DROP TABLE 02703_rqtable_default;

SELECT 'Check system.query_log';
SYSTEM FLUSH LOGS;
SELECT query, used_row_policies FROM system.query_log WHERE current_database == currentDatabase() AND type == 'QueryStart' AND query_kind == 'Select' ORDER BY event_time_microseconds;

DROP ROW POLICY 02703_filter_11_db ON *;
DROP ROW POLICY 02703_filter_11 ON 02703_rqtable_default;

USE db1_02703;
SELECT '  -- CREATE DATABASE-LEVEL POLICY IN CURRENT DATABASE';
CREATE ROW POLICY db2_02703 ON * TO u1_02703;
SHOW CREATE POLICY db2_02703 ON *;

DROP ROW POLICY db2_02703 ON *;

DROP USER u1_02703;
